package com.yuncheng.spcyApi.busService;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.yuncheng.spcyApi.constant.xcjchy.SqsxHyConstant;
import com.yuncheng.spcyApi.entity.SpcySqsxHyzt;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 二维码生成
 * @author hua
 */
public class QRCodeService {

    /**
     * 现场检查会议-末次会议签到码-二维码
     * @param sqsxid
     * @param filePath
     * @throws IOException
     * @throws WriterException
     */
    public static void generateSqsxXcjcMshyQRCode(String sqsxid, String filePath, SpcySqsxHyzt hyzt) throws IOException, WriterException {
        String url = "https://bg.yjj.gxzf.gov.cn/gxfdei/onSiteInspectionCheckInSignedVersion?obj=";
        url += "{";
        url += "\"fhyzt\":\"" + hyzt.getFhyzt() + "\",";
        url += "\"id\":\"" + hyzt.getId() + "\",";
        url += "\"frylx\":\""+ "企业" +"\",";
        url += "\"fhylx\":\"" + SqsxHyConstant.HYLX_MCHY + "\",";
        url += "\"sqsxid\":\"" + sqsxid + "\"";
        url += "}";

        int width = 180;
        int height = 180;

        generateQRCode(url, filePath, width, height);
    }

    /**
     * 现场检查会议-满意度调查表-二维码
     * @param sqsxid
     * @param filePath
     * @throws IOException
     * @throws WriterException
     */
    public static void generateSqsxHyMydQRCode(String sqsxid, String filePath) throws IOException, WriterException {
        String url = "https://bg.yjj.gxzf.gov.cn/gxfdei/businessManagementSatisfactionSurvey?obj=";
        url += "{\"sqsxid\":\"" + sqsxid + "\"}";

        int width = 180;
        int height = 180;

        generateQRCode(url, filePath, width, height);
    }

    /**
     * 生成二维码
     * @param url
     * @param filePath
     * @param width
     * @param height
     * @throws WriterException
     * @throws IOException
     */
    private static void generateQRCode(String url, String filePath, int width, int height) throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        Map<EncodeHintType, ErrorCorrectionLevel> hints = new HashMap<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);

        BitMatrix bitMatrix = qrCodeWriter.encode(url, BarcodeFormat.QR_CODE, width, height, hints);

        /** 过期替换 */
//        MatrixToImageWriter.writeToFile(bitMatrix, "PNG", new File(filePath));

        BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
        ImageIO.write(bufferedImage, "PNG", new File(filePath));
    }
}
